package com.pan.behavioral.Interpreter.example.ex01.expression.impl;


import com.pan.behavioral.Interpreter.example.ex01.context.Context;
import com.pan.behavioral.Interpreter.example.ex01.expression.Expression;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class FuncExpression implements Expression {

    private String funcName;
    private String token;
    Expression func;
    private HashMap<String,String> argsMap;{
        argsMap = new HashMap<>();
    }
    private List<String> argNames;{
        argNames = new ArrayList<>();
    }
    protected List<String> getArgNames(){
        return this.argNames;
    }
    protected String getArg(String key){
        if (argsMap.containsKey(key)){
            return argsMap.get(key);
        }else {
            throw new RuntimeException("该参数不存在："+key);
        }
    }

    public FuncExpression(){

    }

    @Override
    public void interpreter(Context context) {
        //todo: 重构这个方法

















        token = context.currentStatement();
        if (token.equals("func")) {
            String nameArgs = context.nextStatement();
            Pattern funcNamePattern = Pattern.compile("^\\w+(?=\\()");
            Matcher funcNameMatcher = funcNamePattern.matcher(nameArgs);
            if (funcNameMatcher.find()){
                funcName = funcNameMatcher.group();
            }else {
                throw new RuntimeException("错误函数名："+nameArgs);
            }
            Pattern funcArgsPattern = Pattern.compile("(?<=^"+funcName+"\\()(\\s*|\\w+|(\\w+,)+\\w+)(?=\\))");
            Matcher funcArgsMatcher = funcArgsPattern.matcher(nameArgs);
            if (funcArgsMatcher.find()) {
                String args = funcArgsMatcher.group();
                args = args.strip();
                if (args.length()!=0){
                    String[] argArr = args.split(",");
                    for (String argName : argArr) {
                        argsMap.put(argName,null);
                        argNames.add(argName);
                    }
                }
            }else {
                throw new RuntimeException("错误函数定义参数："+nameArgs);
            }
            func = new MyExpression();
            func.interpreter(context);
        }else {
            throw new RuntimeException("该token不是函数定义："+token);
        }

    }

    public FuncExpression setArgs(String... args){
        if (args.length != argNames.size()){
            throw new RuntimeException(funcName+"函数调用参数错误");
        }
        for (int i = 0; i < argNames.size(); i++) {
            String key = argNames.get(i);
            String value = args[i];
            argsMap.put(key,value);
        }
        return this;
    }


    @Override
    public String execute(){
        return func.execute();
    }
}
